package com.caohx.bms.exception;

import com.caohx.bms.pojo.ResponseMessage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice  //统一处理
public class GlobalExceptionHandlerAdvice {

    Logger log  = LoggerFactory.getLogger(GlobalExceptionHandlerAdvice.class);

    @ExceptionHandler({Exception.class})  //什么异常统一处理
    public ResponseMessage handleException(Exception e, HttpServletRequest request, HttpServletResponse response)
    {
        log.error("统一异常",e);
        ResponseMessage responsemessage = new ResponseMessage();
        responsemessage.setCode(500);
        responsemessage.setMessage("excepiton");
        responsemessage.setData(e.getMessage());
        return responsemessage ;
    }



    //对校验类错误特别处理，显示校验错误，方便用户修改
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ResponseMessage> handleValidationExceptions(
            MethodArgumentNotValidException ex, HttpServletRequest request) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });

        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setCode(HttpStatus.BAD_REQUEST.value());
        responseMessage.setMessage("Validation Error");
        responseMessage.setData(errors);

        return new ResponseEntity<>(responseMessage, HttpStatus.BAD_REQUEST);
    }
}
